package app.listener

import app.comet.Subscriber
import im.mange.shoreditch.engine.ScriptEventListener
import im.mange.shoreditch.hipster._
import org.joda.time.LocalDateTime
import app.server.{ValidatedTestRun, UpdateTestRun, StoppedTestRun, StartedTestRun}
import app.server.UpdateTestRun
import im.mange.shoreditch.hipster.VersionedService
import im.mange.shoreditch.hipster.Check
import im.mange.shoreditch.hipster.Action
import app.server.StartedTestRun
import app.server.ValidatedTestRun
import app.server.StoppedTestRun
import im.mange.shoreditch.engine.model.Test
import im.mange.shoreditch.engine.model.Test

//TODO: this needs a TestContext that is a non destructive Script summariser
case class CometListener(subscriber: Subscriber, test: Test) extends ScriptEventListener {
  override def beforeStarted(script: Script, testId: String) {}
  override def validated(testRunId: String, versionedServices: List[VersionedService]) { subscriber ! ValidatedTestRun(test.id, testRunId, versionedServices) }
  override def started(when: LocalDateTime, script: Script) { subscriber ! StartedTestRun(test.id, script.steps, script.duration, script.testRunId.get) }
  override def stopped(when: LocalDateTime, script: Script) { subscriber ! StoppedTestRun(test.id, script.duration, script.successful, script.startedAt, script.abortedBecause) }

  override def running(step: Step) {
    //TODO: reasons stating to look a bit iffy here ...
    subscriber ! UpdateTestRun(test.id, step, Nil, step.script.duration)
  }

  override def failure(action: Action, reasons: List[String]) { subscriber ! UpdateTestRun(test.id, action, reasons, action.script.duration) }
  override def success(action: Action) { subscriber ! UpdateTestRun(test.id, action, Nil, action.script.duration) }
  override def failure(check: Check, reasons: List[String]) { subscriber ! UpdateTestRun(test.id, check, reasons, check.script.duration) }
  override def success(check: Check) { subscriber ! UpdateTestRun(test.id, check, Nil, check.script.duration) }
}
